package com.rowline.admin.module.study.thread;

/**
 * ClassName:ThreadLocal
 * Created by 245167
 * on 2017/12/8  08:42
 * description:
 */
public class ThreadLocalTest {

    public static class MyRunnable implements Runnable{

        private ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();

        @Override
        public void run() {
            threadLocal.set((int) (Math.random() * 100D));
            try{
                Thread.sleep(5000);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            System.out.println(threadLocal.get());
        }
    }




    public static void main(String[] args) throws InterruptedException {
        ThreadLocal myThreadLocal = new ThreadLocal();
        myThreadLocal.set("hello world");
        String s = (String)myThreadLocal.get();
        System.out.println("ThreadLocal 变量：" + s);

        ThreadLocal<String> myThreadLocal2 = new ThreadLocal<String>();
        myThreadLocal2.set("hello kitty");
        String s2 = myThreadLocal2.get();
        System.out.println("ThreadLocal2 变量：" + s2);

        ThreadLocal<String> myThreadLocal3 = new ThreadLocal<String>(){
            @Override
            protected String initialValue(){
                return "This is the initialValue";
            }
        };

        MyRunnable sharedRunnableInstance = new MyRunnable();
        Thread thread1 = new Thread(sharedRunnableInstance);
        Thread thread2 = new Thread(sharedRunnableInstance);

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

    }

}
